#!/bin/sh -x
# $Id: feedtime-install.cgi 40 2009-10-03 01:04:20Z lordylordy $
INSTALL_DIR=$( echo "$0" | sed -r 's/[^/]+$//' )
INSTALL_DIR=$( cd "$INSTALL_DIR" ; pwd )

start_command="$INSTALL_DIR/feedtime.sh reboot"
appname="feedtime"
wsname="FeedTime"
maincgi="feedtime.cgi"
mainsh="feedtime.sh"
httpd="http://127.0.0.1:8883"

NMT="$INSTALL_DIR/install.sh"

echo "Content-Type: text/html"
echo

case `"$NMT" NMT_VERSION` in
    *-408)
        arch=nmt200
        crondir=/etc/cron
        ;;
    *-40[23])
        arch=nmt100
        crondir=/etc
        ;;
    *) 
        arch=other
        crondir=/dev/null
        echo unknown nmt
        exit 1
        ;;
esac

PERMS() {
    chmod -R 775 "$INSTALL_DIR"
    chown -R nmt:nmt "$INSTALL_DIR"
}

DO() {
    ( echo "****** $1 ******" ;\
    echo "-----------------------------------------------------------" ;\
    eval "$1" ;\
    echo "==========================================================="\
    ) >> "$INSTALL_DIR/check.log" 2>&1
}

CP() {
    if [ -e "$1" ] ; then
        cp "$1" "$2"
    fi
}

case "$1" in 
    install)
        PERMS

        # Now add new stuff
        "$NMT" NMT_INSTALL_WS "$wsname" "$httpd/$maincgi"
        "$NMT" NMT_INSTALL "$appname" "$start_command"

        # If the old tvnzb is installed copy the settings and uninstall it.
        oldtvnzb=/share/Apps/tvnzb/data
        if [ -d $oldtvnzb -a ! -f $INSTALL_DIR/data/.copied ] ; then
            if [ -f $oldtvnzb/tvnzb.active ] ; then
                mv $oldtvnzb/tvnzb.active $INSTALL_DIR/feedtime.active
            fi
            CP $oldtvnzb/tvnzb.cfg $INSTALL_DIR/data/feedtime.cfg
            CP $oldtvnzb/feeds $INSTALL_DIR/data/feeds
            rm -fr $INSTALL_DIR/data/feed_[0-9]*
            cp -a $oldtvnzb/feed_[0-9]* $INSTALL_DIR/data/.
            touch $INSTALL_DIR/data/.copied
            # Uninstall the old one
            if [ -f /share/Apps/tvnzb ] ; then
                ( cd /share/Apps/tvnzb ; ./tvnzb-install.cgi uninstall )
            fi
        fi
        PERMS
        $start_command
        "$NMT" NMT_INSTALL_WS_BANNER "FeedTime" "Installation Complete"

        ;;
    uninstall)
        "$INSTALL_DIR/feedtime.sh" stop
        rm -f "/opt/sybhttpd/default/$appname.cgi"
        "$NMT" NMT_UNINSTALL "$appname"
        "$NMT" NMT_UNINSTALL_WS "$wsname" 
        "$NMT" NMT_LINE_REMOVE $appname $crondir/cron.weekly

        "$NMT" NMT_CRON_DEL nmt "$appname.nzbget_weekend"
        "$NMT" NMT_CRON_DEL nmt "$appname.nzbget_weekday"
        "$NMT" NMT_CRON_DEL nmt "$appname.nzbget_check"

        "$NMT" NMT_CRON_DEL nmt "$appname"
        "$NMT" NMT_INSTALL_WS_BANNER "FeedTime" "Uninstalled"
        ;;
    check)
        "$NMT" NMT_CHECK "$INSTALL_DIR"
        "$NMT" NMT_INSTALL_WS_BANNER "$wsname" "Output in check.log"
        PERMS
        ;;
esac
